/* Generic Create command for salesforce */
package poler.control.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.salesforce.AsyncResponder;
	import com.salesforce.objects.SObject;
	
	import mx.rpc.IResponder;
	import mx.utils.ObjectUtil;
	
	import poler.classes.AbstractCommand;
	import poler.control.events.CreateEvent;
	import poler.control.events.Save64Event;
	import poler.model.ModelLocator;

	
	
	public class Save64Cmd extends AbstractCommand implements ICommand, IResponder
	{
		private var _amLocator:ModelLocator = ModelLocator.getInstance();
		private var cFunction:Function;
		private var Arr:Array;
		private var cId:String;
		private var Count:int = 0;
		
		public function execute(event:CairngormEvent):void
		{

			if((event as Save64Event).Callback != null){
				cFunction = (event as CreateEvent).Callback;
			}
			cId =  (event as Save64Event).ContactId;
			Arr =  (event as Save64Event).Context;
			//
			Arraysave(Count);
		}
		private function Arraysave(index:int):void{
			var sarr:Array = new Array();
			if(cId.length > 0){
				var vo:SObject = new SObject('ImageDetail__c');
				vo.Data__c = Arr[index];
				vo.Contact__c = cId;
				vo.Stack__c = index;
				sarr.push(vo);
				if(_amLocator.dmView1.acContactIds.length > 0){
					deleteExisting(sarr);
				}else{
					saveData(sarr);
				}
			}
		}
		private function saveData(ar:Array):void{
			_amLocator.Apex.create(ar ,new AsyncResponder(result,faultH));	
		}
		private function deleteExisting(ar:Array):void{
			var aCID:Array = _amLocator.dmView1.acContactIds; 
			var fn:Function = function(obj:Object):void{
				trace('Image Base64 String Object Deleted: ');
				trace('acContactId: '+_amLocator.dmView1.acContactIds.length);
			};
			//
			_amLocator.Apex.deleteIds(_amLocator.dmView1.acContactIds, new AsyncResponder(fn,faultH));
			_amLocator.dmView1.acContactIds = new Array();
			//
			_amLocator.Apex.create(ar ,new AsyncResponder(result,faultH));
		}
		private function faultH(data:Object):void{
			trace('error faultH: '+ObjectUtil.toString(data));
		}
		public function result(data:Object):void
		{	
			Count++;
			trace('Count: '+Count+' arr.l: '+Arr.length);
			if(Count <= Arr.length){
				Arraysave(Count);
			}
		}
		
	}
}